<?php
namespace app\kucun\controller;

use app\kucun\model\ProductStockLogModel;
use app\kucun\model\ProductStockModel;
use app\kucun\model\ShopModel;

/**
 * Class Index
 * @package app\index\controller
 */
class Debash extends Base
{

    // 获取首页数据
    public function homeData(){

        // 已店铺为维度，统计店铺下的产品数量，库存数量，今日入库多少产品，出库多少产品
        // 店铺列表
        $shop_list = (new ShopModel())->where(['status' => 1])->select();
        $result = [];

        $map = [];
        $map[] = ['create_time', 'between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
        $today_stock_count_arr = ProductStockLogModel::where($map)->group('option_shop_id,option_id')->field("option_shop_id, option_id, count(distinct stock_id) as num")->select();


        $stock_count_arr = ProductStockModel::where(['status' => 1])->group("shop_id")->field("shop_id, count(id) as stock_count")->select();

        foreach ($shop_list as $shop){

            $stock_count = 0;
            foreach ($stock_count_arr as $stock_count_item){
                if($stock_count_item['shop_id'] == $shop['id']){
                    $stock_count = $stock_count_item['stock_count'];
                    break;
                }
            }

            $today_in_stock_count = 0;
            $today_out_stock_count = 0;
            $today_seal_stock_count = 0;
            foreach ($today_stock_count_arr as $today_stock_count_item){
                if($today_stock_count_item['option_shop_id'] == $shop['id']){
                    if($today_stock_count_item['option_id'] == 1){
                        $today_in_stock_count = $today_stock_count_item['num'];
                    }elseif($today_stock_count_item['option_id'] == 2){
                        $today_out_stock_count = $today_stock_count_item['num'];
                    }elseif($today_stock_count_item['option_id'] == 3){
                        $today_seal_stock_count = $today_stock_count_item['num'];
                    }
                }
            }


            // $product_count = ProductStockModel::where(['shop_id' => $shop['id'], 'status' => 1])->count();    
            $result[] = [
                'shop_id' => $shop['id'],
                'shop_name' => $shop['shop_name'],
                'product_count' => 0,
                'stock_count' => $stock_count,
                'today_in_stock_count' => $today_in_stock_count,
                'today_out_stock_count' => $today_out_stock_count,
                'today_seal_stock_count' => $today_seal_stock_count,
            ];
        }

        return $this->returnSuccess([
            'shop_data' => $result
        ]);

    }
}